<?php

namespace app\admin\controller;

use app\admin\model\user;
use think\Controller;
use think\Db;
use think\Request;

class Login extends Controller
{
    /**
     * 获取当前登录用户权限菜单id
     * */
    public function getUserAuthMenuId($uid)
    {
        $rules_list = Db::name('auth_group_access')->alias('a')->field('g.rules')->join('auth_group g', 'a.group_id = g.id')->where(['a.uid' => $uid, 'g.status' => 1])->select();
        if ($rules_list) {
            $new_rules = '';
            foreach ($rules_list as &$v) {
                if ($new_rules == '') {
                    $new_rules = $v['rules'];
                } else {
                    $new_rules = $new_rules . ',' . $v['rules'];
                }
            }
            //数组去重
            $new_rules_arr = array_unique(explode(',', $new_rules));

            return $new_rules_arr;
        } else {
            return [];
        }
    }

    public function login()
    {
        if (session('id') && session('account')) {
            $id = session('id');
            if ($id > 1) {
                $user_rules_arr = $this->getUserAuthMenuId($id);
                $auth_where['id'] = ['IN', $user_rules_arr];
                $menu = Db::name('menu')->field('url')->where(['level' => ['gt', 2], 'status' => 1, 'is_show' => 1])->where($auth_where)->order('sort asc')->select();
                $url = $menu[0]['url'];
            } else {
                $url = C('DEFAULT_URL');
            }

            $this->redirect($url);
        } else {
            if (request()->isPost()) {
                $input = request()->param();

                $token = $input['__token__'];
                $account = $input['login_account'];
                $password = $input['login_password'];
//                $code = $input['login_code'];

                if (checkToken($token)) {
                    if (empty($account)) adminReturn(3, '请输入账号');
                    if (empty($password)) adminReturn(3, '请输入密码');
//                    if (empty($code)) adminReturn(3, '请输入验证码');
//                    if (!captcha_check($code)) adminReturn(3, '验证码错误');

                    $where['account'] = $account;
                    $admin = model('user')->getAdminByUsername($where);
                    if ($admin) {
                        // 检查密码
                        if (thinkEncrypt($password) != $admin->password) adminReturn(3, '密码错误');
                        // 检查状态
                        if ($admin->status == 2) adminReturn(3, '用户被禁用，请联系管理员');

                        if ($admin->id > 1) {
                            $user_rules_arr = $this->getUserAuthMenuId($admin['id']);
                            $auth_where['id'] = ['IN', $user_rules_arr];
                            $menu = Db::name('menu')->field('url')->where(['level' => ['gt', 2], 'status' => 1, 'is_show' => 1])->where($auth_where)->order('sort asc')->select();
                            if (empty($menu)) adminReturn(3, '该账号无权限', url('/admin/login/login'));
                        }

                        // 登录成功

                        //记录session
                        session('id', $admin->id);
                        session('account', $admin->account);

                        //记录日志
                        $log_data = [
                            'user_id' => $admin->id,
                            'username' => $account,
                            'ip' => $_SERVER['REMOTE_ADDR'],
                            'create_time' => time()
                        ];
                        Db::name('login_log')->insert($log_data);

                        adminReturn(1, '登录成功', $admin->id > 1 ? $menu[0]['url'] : C('DEFAULT_URL'));
                    } else {
                        adminReturn(3, '登录失败');
                    }
                } else {
                    adminReturn(3, '系统繁忙，请稍后再试~');
                }
            } else {
                return $this->fetch();
            }
        }
    }
}
